package com.cdu.guoxinan.www.smartcom.service.impl;
import com.cdu.guoxinan.www.smartcom.domian.dto.ProductQueryDTO;
import com.cdu.guoxinan.www.smartcom.domian.pojo.Product;
import com.cdu.guoxinan.www.smartcom.mapper.ProductMapper;
import com.cdu.guoxinan.www.smartcom.service.ProductService;
import com.cdu.guoxinan.www.smartcom.tool.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private OssUtil ossUtil;

    @Override
    public List<Product> getAllProducts() {
        return productMapper.findAll();
    }

    @Override
    public List<Product> getProductsByCategoryAndName(String category, String name) {
        return productMapper.findByCategoryAndName(category, name);
    }

    @Override
    public PageInfo<Product> queryPage(ProductQueryDTO productQueryDTO) {
        PageHelper.startPage(productQueryDTO.getPage(), productQueryDTO.getLimit());
        List<Product> list = productMapper.queryPage(productQueryDTO);
        PageInfo<Product> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
    
    @Override
    public void addProduct(Product product) {
        productMapper.insert(product);
    }

    @Override
    public void updateProduct(Product product) {
        // 获取原商品信息，用于删除旧图片
        Product oldProduct = productMapper.findById(product.getProductId());
        if (oldProduct != null && oldProduct.getImageUrl() != null &&
            !oldProduct.getImageUrl().equals(product.getImageUrl())) {
            // 如果图片URL发生了变化，删除旧图片
            ossUtil.deleteFile(oldProduct.getImageUrl());
        }
        productMapper.update(product);
    }

    @Override
    public void deleteProduct(Long productId) {
        // 获取商品信息，用于删除图片
        Product product = productMapper.findById(productId);
        if (product != null && product.getImageUrl() != null) {
            // 删除OSS中的图片文件
            ossUtil.deleteFile(product.getImageUrl());
        }
        // 删除数据库中的商品记录
        productMapper.deleteById(productId);
    }
} 